<%--
  Created by IntelliJ IDEA.
  User: CM
  Date: 17/5/30
  Time: 下午11:00
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>商铺首页配置</title>
    <jsp:include page="../../common/header.jsp"></jsp:include>
    <jsp:include page="../../common/cloud-head.jsp"></jsp:include>
    <jsp:include page="../../common/dt.jsp"></jsp:include>
    <style>
        #areaSelectBox > div {
            display: inline-block;
            width: 166px;
        }

        #dateRange {
            display: inline-block;
            width: 15rem;
        }

        #linkInputBox {
            display: block;
        }

        .card-content {
            min-height: 83px;
        }

        #articleSelectBox, #goodSelectBox {
            display: none;
        }
    </style>
</head>
<body>
<div class="col-md-12">
    <div class="card">
        <div class="card-action">
            <label>轮播图配置</label>
            <button class="btn btn-primary" data-toggle="modal" onclick="$('#addDialog').modal('show')">添加轮播图
            </button>
        </div>
        <div class="card-content">
            <table id="mainTable" cellpadding="0" cellspacing="0" border="0" class="auto-table">
                <thead>
                <tr>
                    <th>图片</th>
                    <th>投放时间</th>
                    <th>投放内容</th>
                    <th>投放区域</th>
                    <td>操作</td>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="addDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    添加轮播图
                </h4>
            </div>
            <div class="modal-body">
                <div>
                    <div class="form-group col-md-6">
                        <label>有效时间</label>
                        <input type="text" value="" placeholder="点击选择时间范围" name="dateRange" id="dateRange"/>
                    </div>
                    <div>
                        <div class="form-group" id="areaSelectBox">
                            <label>投放区域</label>
                            <select name="city" id="city" class="chosen-select">
                                <option value="default">默认全国</option>
                                <c:forEach items="${citys}" var="city">
                                    <option value="${city.addressId}">${city.name}</option>
                                </c:forEach>
                            </select>
                        </div>
                        <div class="clear"></div>
                        <div class="col-md-6">
                            <label>响应类型</label>
                            <select name="type" id="type" style="display: inline-block;width:10rem;"
                                    onchange="changeValueShow()">
                                <option value="LINK" selected>链接</option>
                                <option value="GOOD">商品</option>
                                <option value="ARTICLE">文章</option>
                            </select>
                        </div>
                        <div class="col-md-6" id="linkInputBox">
                            <input placeholder="请输入合法的链接" id="linkInput" type="text"/>
                        </div>
                        <div class="col-md-6" id="articleSelectBox">
                            <select id="articleSelect">

                            </select>
                        </div>
                        <div class="col-md-6" id="goodSelectBox">
                            <select id="goodSelect">

                            </select>
                        </div>
                        <div class="clear"></div>
                    </div>
                </div>
                <div class="clear"></div>
                <div>
                    <div class="form-group upload-img-box">
                        <label>选择图片</label>
                        <img id="preveiw1" name="preveiw1" class="img_upload_preview" for="upfile" data-target="img1"
                             src=""
                             onclick="$('#upfile').click()"
                             onerror="this.src='${ctx}/resources/ueditor/dialogs/image/images/image.png'"/>
                        <input id="upfile" type="file" name="upfile" style="display: none;"
                               onchange="uploadFile('upfile','preveiw1','uri','image')"/>
                        <input name="uri" id="uri" type="hidden">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消
                </button>
                <button type="button" class="btn btn-primary" onclick="addCarousel()">
                    提交
                </button>
            </div>
        </div>
    </div>
</div>


<script type="text/html" id="carouselTmpl">
    <tr>
        <td>
            <img data-src="\${thumb_url}" onerror="this.src='\${url}'" style="width:12rem;max-height:8rem;"/>
        </td>
        <td>
            <p><code>开始时间</code> \${formatDate(startTime)}</p>
            <p><code>结束时间</code> \${formatDate(endTime)}</p>
        </td>
        <td>
            <span>\${type_desc}</span>
            {{if type == "LINK"}}
            <a href="\${value}">\${value}</a>
            {{else}}
            <div class="target-value" data-value="\${value}" data-type="\${type}">
                <i class="fa fa-spin fa-spinner">Loading</i>
            </div>
            {{/if}}
        </td>
        <td>
            \${city_desc}
        </td>
        <td>
            <button class="btn btn-danger" onclick="delCarousel('\${cid}')">删除</button>
        </td>
    </tr>
</script>

<script>
    var dt;
    $(function () {
        dt = $("#mainTable").dataTable({
            fnDrawCallback: function () {
                $("img[data-src]").each(function () {
                    $(this).attr("src", $(this).attr("data-src"));
                })
                loadGoodInfo();
            }
        });
        loadArticle();
        loadCarouselList();
        loadGoodChosen();
        $("#city").chosen({
            width: 200,
            height: 33,
            "no_results_text": "未找到对应的区域"
        });
    })

    function addCarousel() {
        var data = {
            uri: $("#uri").val() || "",
            startTime: $("#dateRange").val() ? $("#dateRange").val().split(" to ")[0] : "",
            endTime: $("#dateRange").val() ? $("#dateRange").val().split(" to ")[1] : "",
            city: $("#city").val() || "",
            type: $("#type").val() || ""
        };

        if (data["type"] == "LINK") {
            data["typeValue"] = $("#linkInput").val()
        } else if (data["type"] == "GOOD") {
            data["typeValue"] = $("#goodSelect").val()
        } else if (data["type"] == "ARTICLE") {
            data["typeValue"] = $("#articleSelect").val()
        }

        if (isEmpty(data["uri"])) {
            bootbox.alert("轮播图片不能为空!");
            return -1;
        }
        if (isEmpty(data["startTime"]) || isEmpty(data["endTime"])) {
            bootbox.alert("请选择时间区间!");
            return -1;
        }

        if (isEmpty(data["city"])) {
            bootbox.alert("请选择投放城市!");
            return -1;
        }
        var scope = "SHOP";
        asyncAjax({
            url: ctx + "/portal/config/carousel/" + scope + "/add?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == "0") {
                    $("#addDialog").modal("hide");
                    var htmlArray = [];
                    var tds = $("#carouselTmpl").tmpl(res["data"]).find("td");
                    $.each(tds, function (idx, el) {
                        htmlArray.push($(el).html());
                    })
                    dt.fnAddData([htmlArray]);
                } else {
                    bootbox.alert(res["msg"]);
                }
            }
        })
    }

    function loadCarouselList() {
        var data = {shopId:'${uid}'};
        asyncAjax({
            url: ctx + "/portal/config/carousel/list/SHOP?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            beforeSend: function (req) {
                dt.fnClearTable();
            },
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == "0") {
                    var dataArray = [];
                    $.each(res["data"], function (idx, carousel) {
                        var htmlArray = [];
                        var tds = $("#carouselTmpl").tmpl(carousel).find("td");
                        $.each(tds, function (idx, el) {
                            htmlArray.push($(el).html());
                        })
                        dataArray.push(htmlArray);
                    })

                    dt.fnAddData(dataArray);

                } else {
                    bootbox.alert(res["msg"]);
                }
            }
        })
    }

    function delCarousel(cid) {
        bootbox.confirm({
            title: '提示',
            message: '确定删除此轮播图么？',
            buttons: {
                confirm: {
                    label: "确定"
                },
                cancel: {
                    label: '取消'
                }
            },
            callback: function (res) {
                if (res == true) {
                    var data = {cid: cid};
                    asyncAjax({
                        url: ctx + "/portal/config/carousel/del?" + $.param(data).replace(/(%5D|%5B)/g, ""),
                        success: function (res) {
                            //console.log("res:%o", res);
                            if (res["result"] == "0") {
                                loadCarouselList();
                            } else {
                                bootbox.alert(res["msg"]);
                            }
                        }
                    })
                }
            }
        })

    }

    function changeValueShow() {
        var type = $("#type").val();
        switch (type) {
            case "LINK":
                $("#goodSelectBox,#articleSelectBox").hide("slow", function () {
                    $("#linkInputBox").show("slow");
                });
                break;
            case "GOOD":
                $("#linkInputBox,#articleSelectBox").hide("slow", function () {
                    $("#goodSelectBox").show("slow");
                });
                break;

            case "ARTICLE":
                $("#goodSelectBox,#linkInputBox").hide("slow", function () {
                    $("#articleSelectBox").show("slow");
                });
                break;

        }
    }

    var GOOD_CACHE = {};
    function loadGoodChosen() {
        var data = {
            status: 1
        };
        asyncAjax({
            url: ctx + "/goodMgr/good/list?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            success: function (res) {
                //console.log("res:%o", res);
                $("#goodSelect,#addGoodSelect").html("");
                if (res["result"] == "0") {
                    $.each(res["data"]["goods"], function (id, good) {
                        GOOD_CACHE[good["good_id"]] = good;
                        $("#goodSelect").append('<option value=\"' + good["good_id"] + '\">' + good['goodName'] + '</option>')
                    })
                    $("#goodSelect").chosen({width: 240})
                    loadGoodInfo();
                } else {
                    bootbox.alert(res["msg"]);
                }
            }
        })
    }

    function loadGoodInfo() {
        $(".target-value[data-type=\"GOOD\"]").each(function (idx, el) {
            var good = GOOD_CACHE[$(this).attr("data-value")];
            $(this).html((good ? good["goodName"] : "<code>关联商品已经失效</code>"));
        })
    }




    function loadArticle() {
        var data = {
            type: 1,
            uuid: 0
        };
        asyncAjax({
            url: ctx + "/article/getArticleList?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == "0") {
                    if (!isEmpty(res["data"])) {
                        $.each(res["data"], function (idx, item) {
                            $("#articleSelect").append("<option value=\"" + item["id"] + "\">" + item["main_title"] + "</option>");
                        })

                        $("#articleSelect").chosen({width: 240});
                    } else {
                        bootbox.alert("没有文章信息，如果需要配置资讯请先配置文章内容;");
                    }
                } else {

                }
            }
        })
    }
</script>
</body>
</html>
